﻿# -*- coding: utf-8 -*-
import os
import wsgiref.handlers
import struct
import time
import urllib
import logging
from StringIO import StringIO

from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.ext.webapp import template
#from google.appengine.api import users #extended as "import users"
from google.appengine.api import images
from google.appengine.api import memcache
from google.appengine.api import urlfetch

from functools import *
from django.utils import simplejson
import filters

from irhelper import *
from models import *
import users

website_url = "http://imageroll.appspot.com/"

class MyPage(webapp.RequestHandler):
        def get(self):
            user = users.get_local_user()
            if not user:
                return self.redirect(users.create_login_url("/mypage/"))
            return self.redirect("/user/"+str(user.key().id()))
            
class UserPage(webapp.RequestHandler):
        def get(self,user_id):
            if users.is_current_user_admin():
                    admin = True
            else:
                    admin = False
            user = LocalUser.get_by_id(int(user_id))
            if not user:
                    self.error(404)
                    return self.response.out.write("Oops! 没有找到这个用户...")
            entries = Entry.all().filter("author =", user).order('-date')
            tmpl = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'user_page.html'))
            headers = {'Content-Type': 'text/html',
                     'Last-Modified': time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                                                                    time.gmtime())}
            current_user = users.get_local_user()
            response = template.render(tmpl, {'entries': entries,
#                                            'paginator': paginator,
                                                        'admin': admin,
                                                        'current_user': current_user,
                                                        'user': user})
            for header, argument in headers.items():
                    self.response.headers[header] = argument
            return self.response.out.write(response)
            
class MainPage(webapp.RequestHandler):
        def get(self):
            if users.is_current_user_admin():
                    admin = True
            else:
                    admin = False
            entries = Entry.all().order('-date').fetch(10)
            tmpl = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'main.html'))
#            nEntryPerPage = 10
#            page=self.request.get('page')
#            if page:
#                paginator = Paginator(entries, nEntryPerPage, int(page))
#            else:
#                paginator = Paginator(entries, nEntryPerPage)
#            entries =paginator.object_list()

            headers = {'Content-Type': 'text/html',
                                 'Last-Modified': time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                                                                                time.gmtime())}
            current_user = users.get_local_user()
            response = template.render(tmpl, {'entries': entries,
#                                            'paginator': paginator,
                                                        'admin': admin,
                                                        'current_user': current_user})
            for header, argument in headers.items():
                    self.response.headers[header] = argument
            return self.response.out.write(response)
    
class AllImagesPage(webapp.RequestHandler):
        def get(self):
            if users.is_current_user_admin():
                    admin = True
            else:
                    admin = False
            entries = Entry.all().order('-date')
            tmpl = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'all_images.html'))

            headers = {'Content-Type': 'text/html',
                                 'Last-Modified': time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                                                                                time.gmtime())}
            current_user = users.get_local_user()
            response = template.render(tmpl, {'entries': entries,
                                                        'admin': admin,
                                                        'current_user': current_user})
            for header, argument in headers.items():
                    self.response.headers[header] = argument
            return self.response.out.write(response)
            
class GetImageHandler(webapp.RequestHandler):
        def get(self, image_id):
                try:
                        image = None
                        image = Image.get_by_id(int(image_id))
                        if not image:
                                return self.error(404)
                                return self.response.out.write('Image not found')

                        image_data = image.data
                        image_mime = image.mime

                        width = self.request.get('w')
                        height = self.request.get('h')

                        if width and height:
                                width=int(width)
                                height=int(height)

                                if image.width > width or image.height > height:
                                        image = images.Image(image_data)
                                        image.resize(width, height)
                                        image_data = image.execute_transforms(images.JPEG)
                                        image_mime = 'image/jpeg'

                        headers = {'Content-Type': str(image_mime),
                                             'Cache-Control': 'max-age=2592000'}
                        data = image_data

                        for header, argument in headers.items():
                                self.response.headers[header] = argument
                        return self.response.out.write(data)

                except:
                        return self.error(404)

class DeleteReplyHandler(webapp.RequestHandler):
        def get(self, id):
                # User must be logged in to delete
                if not users.is_current_user_admin():
                        self.error(401)
                        return self.response.out.write('Oops! Unauthorized to delete.')
                reply = Reply.get_by_id(int(id))
                if not reply:
                        self.error(404)
                        return self.response.out.write('Reply not found')
                reply.delete()

                return self.redirect(self.request.get("redirect_to") or '/')

class NewReplyHandler(webapp.RequestHandler):
        def post(self, id):
                if not users.get_local_user():
                    self.error(400)
                    return self.response.out.write('请先登陆！')
                
                try:
                    entry_id = self.request.get("entry_id")
                    entry = Entry.get_by_id(int(entry_id))
                except:
                    self.error(400)
                    return self.response.out.write('Entry not found.')
                reply = Reply(comment=self.request.get("comment"), author=users.get_local_user(), entry=entry)
                reply.put()
                return self.redirect(self.request.get("redirect_to") or '/entry/'+entry_id)

class DeleteEntryHandler(webapp.RequestHandler):
        def get(self, id):
                # User must be logged in to delete
                if not users.get_local_user():
                        self.redirect(users.create_login_url(self.request.uri))
                        return
                if not users.is_current_user_permitted(Entry, id):
                        self.error(401)
                        return self.response.out.write('Oops! Unauthorized to delete. It seems like you are not the owner of this entry?')
                entry = Entry.get_by_id(int(id))
                if not entry:
                        self.error(404)
                        return self.response.out.write('Entry not found')
                entry.delete()

                return self.redirect(self.request.get("redirect_to") or '/')

class NewEntryHandler(webapp.RequestHandler):
        def get(self, reference):
            # User must be logged in to edit
            if not users.get_local_user():
                self.redirect(users.create_login_url(self.request.uri))
                return

            image_url = self.request.get("url")
            image_purl = self.request.get("purl")

            tmpl = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'new.html'))
            headers = {'Content-Type': 'text/html',
                                 'Last-Modified': time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                                                                                time.gmtime())}
            user = users.get_local_user()
            response = template.render(tmpl, {'url': image_url,
                                              'purl': image_purl,
                                                'user': user,
                                                'website_url':website_url})

            for header, argument in headers.items():
                    self.response.headers[header] = argument
            return self.response.out.write(response)

        def post(self, reference):
                # User must be logged in to edit
                if not users.get_local_user():
                    self.error(400)
                    return self.response.out.write('请先登陆！')
                entry = Entry(comment=self.request.get("comment"), image_url = self.request.get("url"),image_purl = self.request.get("purl"))

                
                if entry.image_url:
                    entry.image = save_image_from_url(entry.image_url)

                if not entry.image:
                    return self.response.out.write("获取/保存图像失败...")

                user = users.get_local_user()
                if user:
                    entry.author = user

                entry.put()

                dont_redirect = self.request.get("dont_redirect")
                if not dont_redirect:
                    return self.redirect('/')
                else:
                    set_cookie(self.response, {'last_sent_image_id':entry.image.key().id(),'last_sent_entry_id':entry.key().id()})
                    return self.response.out.write('<html><body>Uploaded successfully! <a href="/entry/'+str(entry.key().id())+'"> View</a> | <a href="javascript:window.close();">Close</a></body></html>')

class EditEntryHandler(webapp.RequestHandler):
        def get(self, entry_id):
            # User must be logged in to edit
            if not users.get_local_user():
                self.redirect(users.create_login_url(self.request.uri))
                return
            #user must be admin or the author to edit
            if not users.is_current_user_permitted(Entry, entry_id):
                self.error(401)
                return self.response.out.write('Oops! Unauthorized to edit. It seems like you are not the owner of this entry?')

            entry = Entry.get_by_id(int(entry_id))
            if not entry:
                self.error(404)
                return self.response.out.write('Entry not found')

            tmpl = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'edit.html'))
            headers = {'Content-Type': 'text/html',
                                 'Last-Modified': time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                                                                                time.gmtime())}
            user = users.get_local_user()
            response = template.render(tmpl, {'user': user,
                                                                  'entry': entry})

            for header, argument in headers.items():
                    self.response.headers[header] = argument
            return self.response.out.write(response)

        def post(self, reference):
                entry = Entry.get(self.request.get("key"))
                entry.comment=self.request.get("comment")
                entry.put()

                #dont_redirect = self.request.get("dont_redirect")
                dont_redirect = False
                if not dont_redirect:
                    return self.redirect('/entry/'+str(entry.key().id()))
                else:
                    return self.response.out.write('<html><body>Uploaded successfully! <a href="/'+str(entry.key())+'"> View</a> | <a href="javascript:window.close();">Close</a></body></html>')

class LoginHandler(webapp.RequestHandler):
        def get(self):
                self.redirect(users.create_login_url('/'))

class LogoutHandler(webapp.RequestHandler):
        def get(self):
                self.redirect(users.create_logout_url('/'))

class RssHandler(webapp.RequestHandler):
        def get(self):
                entries = Entry.all().order('-date').fetch(30)
                tmpl = os.path.join(os.path.dirname(__file__), 'images.rss')
                headers = {'Content-Type': 'text/xml; charset=UTF-8',
                                     'Last-Modified': time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                                                                                    time.gmtime())}
                response = template.render(tmpl, {'entries': entries
                                                                                    })

                for header, argument in headers.items():
                        self.response.headers[header] = argument
                return self.response.out.write(response)

class MemcacheHandler(webapp.RequestHandler):
        def get(self):
                memcache.flush_all()
                self.redirect(users.create_logout_url('/'))

class RPCHandler(webapp.RequestHandler):
    def __init__(self):
        webapp.RequestHandler.__init__(self)
        self.methods = RPCMethods
        
    def post(self,key):
        #only functions named in methods can be called
        methods = ("edit_user_name")
        action = self.request.get("action") or self.request.get("id")
        if action not in methods:
            return self.error(403)
        func = getattr(self, action)
        try:
            result = func()
            return self.response.out.write(result)
        except:
            return self.error(500)
            
    def edit_user_name(self):
        user = users.get_local_user()
        if not user:
            raise Exception("user not found")
        try:
            user.local_name = self.request.get("new_user_name")
            user.put()
        except:
            raise Exception("error while storing new user name")
        return user.local_name
                        
    """ Will handle the RPC requests."""
    def get(self):
        func = None

        action = self.request.get('action')
        if action:
            if action[0] == '_':
                self.error(403) # access denied
            return
        else:
            func = getattr(self.methods, action, None)

        if not func:
            self.error(404) # file not found
        return

        args = ()
        while True:
            key = 'arg%d' % len(args)
            val = self.request.get(key)
            if val:
                args += (simplejson.loads(val),)
            else:
                break
        try:
            result = func(*args)
            self.response.out.write(simplejson.dumps(result))
        except:
            self.error(500)

class RPCMethods:
    """ Defines the methods that can be RPCed.
    NOTE: Do not allow remote callers access to private/protected "_*" methods.
    """
    def Add(self, *args):
        # The JSON encoding may have encoded integers as strings.
        # Be sure to convert args to any mandatory type(s).
        ints = [int(arg) for arg in args]
        return sum(ints)
    
    def edit_user_name(self, *args):
        #args[0]=:new_user_name
        user = users.get_local_user()
        if not user:
            raise Exception("user not found")
        try:
            user.display_name = str(args[0])
            user.put()
        except:
            raise Exception("error while storing new user name")
        return
    
class TestHandler(webapp.RequestHandler):
    """ Will handle the RPC requests."""
    def get(self):
        set_cookie(self.response, 'last_sent_image_id', '1')
        set_cookie(self.response, 'last_sent_entry_id', '2')
        #self.response.headers.add_header('Set-Cookie', 'sdfhiy_key=shit; expires=Fri, 31-Dec-2120 23:59:59 GMT')
        return self.response.out.write('fuck!')

class GetUserHandler(webapp.RequestHandler):
    def get(self,user_nickname):
        pass
        
class GetEntryHandler(webapp.RequestHandler):
        def get(self, entry_id):
                if users.is_current_user_admin():
                        admin = True
                else:
                        admin = False
                entry = None
                try:
                        entry = Entry.get_by_id(int(entry_id))
                except:
                        entry = None
                if not entry:
                        return self.response.out.write('Entry not found')

                tmpl = os.path.join(os.path.dirname(__file__), os.path.join('templates', 'entry_view.html'))
                headers = {'Content-Type': 'text/html',
                                     'Last-Modified': time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                                                                    time.gmtime())}
                user = users.get_local_user()
                data = template.render(tmpl, {'entry': entry,
                                                'admin': admin,
                                                'user': user})

                for header, argument in headers.items():
                        self.response.headers[header] = argument
                return self.response.out.write(data)
